package BM3;

import BM1.ListNode;
import static BM1.ListNode.buildList;

public class Solution3 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k)
    {
        ListNode top = new ListNode(-1);//哨兵节点
        top.next = head;
        ListNode numNode = head;//遍历链表，计算链表长度
        int count = 0;//链表长度
        while (numNode != null)
        {
            numNode = numNode.next;
            count++;
        }
        System.out.println("count的长度是:" + count);
        ListNode pre = top;// 前节点
        ListNode cur = head;// 当前节点
        for (int i = 0; i < (count-count%k)/k;  i++)
        {
            for (int j =0; j < k-1; j++)
            {
               ListNode temp = cur.next;
               cur.next = temp.next;
               temp.next = pre.next;
               pre.next = temp;
            }
            pre = cur;
            cur = cur.next;
        }
        return top.next;
    }
    public static void main (String[] args)
    {
        ListNode head = buildList(1, 2, 3, 4, 5);
        Solution3 s = new Solution3();
        ListNode res = s.reverseKGroup(head,2);
        while (res != null) {
            System.out.print(res.val);
            if (res.next != null) System.out.print("→");
            res = res.next;
        }
    }
}